<template>
  <a-modal v-model:visible="visible" title="报警信息处理" :footer="false" class="alarm-modal" :width="697" centered>
    <div class="alarm-model-body">
      <div class="alarm-model-info flex flex-wrap justify-between">
        <div class="flex items-center flex-wrap justify-between info">
          <div class="flex item items-center">
            <span>站点名称：</span>
            <span>{{ info.stationName }}</span>
          </div>
          <div class="flex item items-center">
            <span>报警时间：</span>
            <span>{{ info.time }}</span>
          </div>
          <div class="flex item items-center">
            <span>报警类型：</span>
            <span>
              {{ render.renderTextValue(info.alarmType, 'alarm_type') }}
            </span>
          </div>
        </div>
        <div class="flex items-center flex-wrap justify-between info">
          <div class="flex item items-center">
            <span>处理结果：</span>
            <span>
              {{ render.renderTextValue(info.handleResult, 'alarm_handle_result') }}
            </span>
          </div>
          <div class="flex item items-center">
            <span>处理时间：</span>
            <span>{{ info.handleTime }}</span>
          </div>
          <div class="flex item items-center">
            <span>告警时长：</span>
            <template v-if="info.status == 1">
              <span>{{ info.time }}</span>
            </template>
            <template v-if="info.status == 2">
              <span>{{ info.handleTime }}</span>
            </template>
          </div>
          <div class="flex item items-center">
            <span>报警级别：</span>
            <span>{{ info.level ? info.level + '级' : '' }}</span>
          </div>
        </div>
        <div class="flex items-center justify-end info">
          <!-- <template v-if="isAssign == false">
            <a-button type="primary" @click="openAssign">下派</a-button>
            <a-divider type="vertical" />
          </template>
          <template v-if="isAssign == true">
            <a-button @click="openAssign">取消</a-button>
          </template> -->
        </div>
      </div>
      <div class="alarm-model-info" style="display: none">
        <div class="tip flex items-center">
          <span>指派工单</span>
        </div>
        <a-form ref="form" :label-col="{ style: { width: '70px' } }">
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item label="处理人">
                <template v-if="isAssign == true">
                  <a-select v-model:value="order.assignTo" placeholder="请选择处理人" allowClear>
                    <a-select-option value="">请选择</a-select-option>
                    <template v-for="(vo, idx) in userList" :key="idx">
                      <a-select-option :value="vo.realname" :label="vo.id">
                        {{ vo.realname }}
                      </a-select-option>
                    </template>
                  </a-select>
                </template>
                <template v-else>
                  {{ order.assignTo ? order.assignTo : '-' }}
                </template>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="联系电话">
                <template v-if="isAssign == true">
                  <a-input v-model:value="order.tel" allowClear placeholder="请输入联系电话" />
                </template>
                <template v-else>
                  {{ order.tel ? order.tel : '-' }}
                </template>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="截至日期">
                <template v-if="isAssign == true">
                  <a-date-picker
                    v-model:value="order.latestHandleTime"
                    show-time
                    placeholder="请输选截至日期"
                    format="YYYY-MM-DD HH:mm:ss"
                    valueFormat="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%"
                  />
                </template>
                <template v-else>
                  {{ order.latestHandleTime ? order.latestHandleTime : '-' }}
                </template>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item>
                <template v-if="isAssign == true">
                  <a-upload
                    name="file"
                    :action="ossAction"
                    multiple
                    v-model:file-list="userList"
                    :headers="tokenHeader"
                    :showUploadList="false"
                    @change="handleUploadChange"
                  >
                    <div class="flex items-center justify-end upload-form-item" title="点击上传文件">
                      <i class="ico"></i>
                      <span>附件上传</span>
                    </div>
                  </a-upload>
                </template>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="工单状态">
                <template v-if="isAssign == true">
                  <JDictSelectTag v-model:value="order.status" placeholder="请选择工单状态" dictCode="order_status" allowClear />
                </template>
                <template v-else>
                  {{ render.renderTextValue(order.status, 'order_status') }}
                </template>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="备注">
                <template v-if="isAssign == true">
                  <a-textarea v-model:value="order.remark" placeholder="请输入备注" allow-clear style="width: 100%" />
                </template>
                <template v-else>
                  {{ order.remark ? order.remark : '-' }}
                </template>
              </a-form-item>
            </a-col>
            <template v-if="fileList.length !== 0">
              <a-col>
                <a-form-item label="文件">
                  <div class="file-list">
                    <template v-for="(vo, idx) in fileList" :key="idx">
                      <span class="item flex justify-between items-center">
                        <a :href="vo.url" target="_blank">{{ vo.name }}</a>
                        <template v-if="isAssign == true">
                          <close-outlined title="删除" @click="onDeleteFileItem(idx)" />
                        </template>
                      </span>
                    </template>
                  </div>
                </a-form-item>
              </a-col>
            </template>
            <template v-if="isAssign == true">
              <a-col :span="24">
                <a-form-item>
                  <div class="flex items-center justify-end">
                    <!-- <a-button type="primary" @click="onSave">保存</a-button>
                    <a-divider type="vertical" /> -->
                    <a-button @click="onConfirmAssign" :loading="loading">确认</a-button>
                  </div>
                </a-form-item>
              </a-col>
            </template>
          </a-row>
        </a-form>
      </div>
    </div>
  </a-modal>
</template>

<script>
import { ref, onMounted, defineComponent, watch, computed } from 'vue';
import { listNoCareTenant } from '/@/views/system/user/user.api';
import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
import { alarmInfoApi, alarmModifyApi, alarmAssignApi } from '/@/api/alarm/index';
import { useUserStore } from '/@/store/modules/user';
import { render } from '/@/utils/common/renderUtils';
import { JDictSelectTag } from '/@/components/Form';
import { useGlobSetting } from '/@/hooks/setting';
import { getToken } from '/@/utils/auth';
import { CloseOutlined } from '@ant-design/icons-vue';

export default defineComponent({
  components: { JDictSelectTag, JUpload, CloseOutlined },
  setup() {
    const userStore = useUserStore();

    const glob = useGlobSetting();

    const tokenHeader = { 'X-Access-Token': getToken() };

    const ROOT_URL = 'http://192.168.1.52:8080/api/sys/common/static/';

    let loading = ref(false);

    let visible = ref(false);

    // 文件列表
    let fileList = ref([]);

    let info = ref({});

    const ossAction = computed(() => `${glob.uploadUrl}/sys/common/upload`);

    let order = ref({
      // 报警ID
      alarmId: '',
      // 处理人
      assignTo: '',
      // 附件
      attachments: '',
      // 截至时间
      latestHandleTime: '',
      // 备注
      remark: '',
      // 状态
      status: '',
      // 联系电话
      tel: '',
    });

    // 是否派单
    let isAssign = ref(false);

    // 用户列表
    let userList = ref([]);

    let statusValue = ref('');

    /**
     * 初始化数据
     */
    function init(id, flag) {
      isAssign.value = flag;
      fileList.value = [];
      alarmInfoApi({ id }).then((res) => {
        info.value = res;
        let data = userStore.getStationList.find((_) => _.stationCode == res.stationCode);
        if (data) {
          info.value['stationName'] = data.name;
        } else {
          info.value['stationName'] = '';
        }

        // 派单报警ID
        order.value.alarmId = info.value.id;

        if (info.value.order !== null) {
          order.value = {
            ...info.value.order,
          };
          let { attachments } = order.value;
          if (attachments) {
            attachments.split(',').map((_) => {
              let url = `${ROOT_URL}${_}`;
              const fileExtension = _.substring(_.lastIndexOf('.') + 1);
              fileList.value.push({
                name: _,
                url,
                type: `.${fileExtension}`,
              });
            });
          }
        }
        statusValue = computed(() => {
          return render.renderTextValue(info.value.status, 'alarm_status');
        });

        getUserList();
      });
    }

    /**
     * 获取用户列表
     */
    function getUserList() {
      let data = {
        pageNo: 1,
        pageSize: 10000000,
      };
      listNoCareTenant(data).then(({ records }) => {
        userList.value = records;
      });
    }

    /**
     * 上传成功后组将成文件列表
     */
    function handleUploadChange(e) {
      if (e.file.response) {
        let fileName = e.file.response.message;
        const fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1);

        let url = `${ROOT_URL}${fileName}`;
        fileList.value.push({
          name: fileName,
          url,
          type: `.${fileExtension}`,
        });
      }
    }

    /**
     * 删除文件
     */
    function onDeleteFileItem(index) {
      fileList.value.splice(index, 1);
    }

    watch(
      () => order.value.assignTo,
      (v) => {
        let data = userList.value.find((_) => _.realname == v);
        if (data) {
          order.value.tel = data.phone;
        }
      }
    );

    /**
     * 打开派单表单
     */
    function openAssign() {
      isAssign.value = !isAssign.value;
    }

    /**
     * 保存数据
     */
    function onSave() {
      alarmModifyApi(info.value).then((res) => {
        init(info.value.id);
      });
    }

    /**
     * 下派单
     */
    function onConfirmAssign() {
      let attachments = [];
      fileList.value.map((_) => {
        attachments.push(_.name);
      });
      let data = {
        ...order.value,
        attachments: attachments.join(','),
      };
      loading.value = true;
      alarmAssignApi(data).then((res) => {
        loading.value = false;
        if (res !== '') {
          init(info.value.id);
        }
      });
    }

    return {
      loading,
      visible,
      info,
      order,
      fileList,
      userList,
      init,
      render,
      statusValue,
      isAssign,
      ossAction,
      tokenHeader,
      handleUploadChange,
      onDeleteFileItem,
      openAssign,
      onSave,
      onConfirmAssign,
    };
  },
});
</script>

<style lang="less" scoped>
.alarm-modal {
  .ant-modal-close {
    .ant-modal-close-x {
      width: 27px;
      height: 27px;
      margin: 9px 20px;
      background: url('@/assets/images/img-16.png') no-repeat;
      cursor: pointer;
      .anticon {
        display: none;
      }
    }
  }
  .ant-modal-header {
    padding: 14.5px 40px;
    background: url('@/assets/images/img-15.png') no-repeat;
    background-size: 100% 100%;
    .ant-modal-title {
      color: #fff;
    }
  }
  .ant-modal-body {
    .alarm-model-body {
      padding: 42px 42px 24px;
      .alarm-model-info {
        &:first-child {
          padding-bottom: 17px;
          // border-bottom: 1px solid rgba(204, 204, 204, 1);
          // box-sizing: border-box;
        }
        .info {
          width: 40%;
          &:last-child {
            width: 100%;
            margin: 0;
          }
          .item {
            width: 100%;
            margin: 0 0 12px;
            span {
              &:first-child {
                width: 100px;
              }
            }
          }
        }
        .tip {
          margin: 30px 0 25px;
          &::before {
            content: '';
            display: block;
            width: 20px;
            height: 23px;
            margin: 0 10.7px 0 0;
            background: url('@/assets/images/img-19.png') no-repeat;
          }
          span {
            color: #333;
          }
        }
        .ant-form {
          max-width: auto;
          .ant-col {
            width: auto;
            .file-list {
              .item {
                width: 100%;
                .anticon {
                  margin: 0 0 0 12px;
                  cursor: pointer;
                  &:hover {
                    svg {
                      background: #40a9ff;
                    }
                  }
                }
              }
            }
            &:last-child {
              .ant-form-item {
                margin-bottom: 0;
              }
            }
          }
          .ant-form-item {
            margin-bottom: 24px;
            .upload-form-item {
              cursor: pointer;
              &:hover {
                color: rgba(42, 130, 228, 1);
              }
              .ico {
                display: block;
                width: 30px;
                height: 30px;
                margin: 0 5px 0 0;
                background: url('@/assets/images/img-18.png') no-repeat;
              }
            }
          }
        }
      }
    }
  }
}
</style>